<template>
  <div class="customer-container">
    <!-- 顶部操作栏 -->
    <div class="action-bar">
      <div class="action-buttons">
        <el-button type="danger" size="default" @click="openAddDialog(null)">
          <el-icon><Plus /></el-icon>
          新增
        </el-button>
        <el-button type="default" size="default" @click="handleBatchDelete">
          删除
        </el-button>
      </div>
      
    </div>

    <!-- 表格 -->
    <el-table 
      ref="tableRef"
      :data="tableData" 
      style="width: 100%" 
      border
      highlight-current-row
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" label="序号" width="60" />
      <el-table-column prop="customercode" label="编码" width="120">
        <template #header>
          <div class="column-header-with-search">
            <span>编码</span>
            <el-icon @click="showColumnSearch.customercode = !showColumnSearch.customercode" class="search-icon">
              <Search />
            </el-icon>
          </div>
          <div v-if="showColumnSearch.customercode" class="column-search">
            <el-input 
              v-model="searchForm.customercode" 
              placeholder="请输入编码" 
              size="small" 
              clearable 
              style="width: 100%"
              @keydown.enter="handleSearch"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="customername" label="名称" width="120">
        <template #header>
          <div class="column-header-with-search">
            <span>名称</span>
            <el-icon @click="showColumnSearch.customername = !showColumnSearch.customername" class="search-icon">
              <Search />
            </el-icon>
          </div>
          <div v-if="showColumnSearch.customername" class="column-search">
            <el-input 
              v-model="searchForm.customername" 
              placeholder="请输入名称" 
              size="small" 
              clearable 
              style="width: 100%"
              @keydown.enter="handleSearch"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="customerrabbreviation" label="简称" width="100" />
      <el-table-column prop="contactinformationofCustomer" label="联系方式" width="180" />
      <el-table-column prop="customerraddress" label="地址" width="200">
        <template #header>
          <div class="column-header-with-search">
            <span>地址</span>
            <el-icon @click="showColumnSearch.address = !showColumnSearch.address" class="search-icon">
              <Search />
            </el-icon>
          </div>
          <div v-if="showColumnSearch.address" class="column-search">
            <el-input 
              v-model="searchForm.address" 
              placeholder="请输入地址" 
              size="small" 
              clearable 
              style="width: 100%"
              @keydown.enter="handleSearch"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="customercreditcode" label="社会信用代码" width="180" />
      <el-table-column prop="createName" label="创建人" width="100">
        <template #header>
          <div class="column-header-with-search">
            <span>创建人</span>
            <el-icon @click="showColumnSearch.createName = !showColumnSearch.createName" class="search-icon">
              <Search />
            </el-icon>
          </div>
          <div v-if="showColumnSearch.createName" class="column-search">
            <el-input 
              v-model="searchForm.createName" 
              placeholder="请输入创建人" 
              size="small" 
              clearable 
              style="width: 100%"
              @keydown.enter="handleSearch"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180">
        <template #default="scope">
          {{ scope.row.createTime ? moment(scope.row.createTime).format('YYYY-MM-DD') : '' }}
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="更新时间" width="180">
        <template #default="scope">
          {{ scope.row.updateTime ? moment(scope.row.updateTime).format('YYYY-MM-DD') : '' }}
        </template>
      </el-table-column>
      <el-table-column><
        <template #header>
          <div class="column-header-with-search">
            <span>更新时间</span>
            <el-icon @click="showColumnSearch.updateTime = !showColumnSearch.updateTime" class="search-icon">
              <Search />
            </el-icon>
          </div>
          <div v-if="showColumnSearch.updateTime" class="column-search">
            <el-input 
              v-model="searchForm.updateTime" 
              placeholder="请输入更新时间" 
              size="small" 
              clearable 
              style="width: 100%"
              @keydown.enter="handleSearch"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="scope">
          <el-button type="danger" size="small" @click="openAddDialog(scope.row)">
            编辑
          </el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <div class="total-count">共 {{ pagination.total }} 条数据</div>
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="prev, pager, next, jumper, sizes"
        :total="pagination.total"
      />
    </div>

    <!-- 添加/编辑弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :before-close="handleClose"
    >
      <el-form ref="formRef" :model="formData" label-width="120px" >
        <el-form-item label="客户编码" prop="customercode">
          <el-input v-model="formData.customercode" placeholder="请输入客户编码" />
        </el-form-item>
        <el-form-item label="客户名称" prop="customername">
          <el-input v-model="formData.customername" placeholder="请输入客户名称" />
        </el-form-item>
        <el-form-item label="客户简称" prop="customerrabbreviation">
          <el-input v-model="formData.customerrabbreviation" placeholder="请输入客户简称" />
        </el-form-item>
        <el-form-item label="联系方式" prop="contactinformationofCustomer">
          <el-input v-model="formData.contactinformationofCustomer" placeholder="请输入联系方式" />
        </el-form-item>
        <el-form-item label="信用代码" prop="customercreditcode">
          <el-input v-model="formData.customercreditcode" placeholder="请输入信用代码" />
        </el-form-item>
        <el-form-item label="客户地址" prop="customerraddress">
          <el-input v-model="formData.customerraddress" placeholder="请输入客户地址" />
        </el-form-item>
        <el-form-item label="客户备注" prop="customercomments">
          <el-input v-model="formData.customercomments" type="textarea" placeholder="请输入客户备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search, Plus, Delete, RefreshLeft, Setting } from '@element-plus/icons-vue';
import { APIs } from '@/Http/http';
import moment from 'moment';
// 表格数据
const tableData = ref<any[]>([]);
const tableRef = ref<any>();
const selectedRows = ref<any[]>([]);
const searchKeyword = ref('');
const searchForm = reactive<any>({
  customercode: '',
  customername: '',
  address: '',
  createName: '',
  updateTime: '',
});
const showColumnSearch = reactive<any>({
  customercode: false,
  customername: false,
  address: false,
  createName: false,
  updateTime: false,
});

// 分页相关
const pagination = reactive({
  currentPage: 1,
  pageSize: 5,
  total: 0,
});

// 弹窗相关
const dialogVisible = ref(false);
const dialogTitle = ref('新增客户');
const formRef = ref<any>();
const formData = reactive<any>({
  customerID: 0,
  customercode: '',
  customername: '',
  customerrabbreviation: '',
  contactinformationofCustomer: '',
  customercreditcode: '',
  customerraddress: '',
  customercomments: '',
  createName: '',
  createTime: '',
  updateTime: '',
});


// 监听分页变化
watch(() => pagination.currentPage, () => {
  getCustomerList();
});

watch(() => pagination.pageSize, () => {
  getCustomerList();
});

// 初始化加载数据
onMounted(() => {
  getCustomerList();
});

// 获取客户列表
const getCustomerList = async () => {
   {
    const params = {
      Pageindex: pagination.currentPage,
      PageSize: pagination.pageSize,
      ...searchForm,
      Keyword: searchKeyword.value
    };
    const response = await APIs.get("/api/Read/GetCustomerList", { params });
    tableData.value = response.data.data.data || [];
    pagination.total = response.data.data.totalCount;
  }
};
const handleSelectionChange = (val: any[]) => {
  selectedRows.value = val;
  console.log(selectedRows.value);
};
const getSelectedRowsArray = () => {
  return selectedRows.value.map(row => ({
    id: row.customerID,
  }));
};

// 实现批量删除功能
const handleBatchDelete = () => {
  const selectedIds = getSelectedRowsArray();
  console.log(selectedRows.value)
  const requestData = {
    ids: selectedIds.map(item => item.id)
  };
  
  ElMessageBox.confirm(
    `确定要删除吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    APIs.post("/api/Write/PLDeleCustomer", requestData).then(res=>{
      if(res.data.code==100) {
        ElMessage.success("批量删除成功");
        getCustomerList();
      }
    })
  });
};
// 打开新增/编辑弹窗
const openAddDialog = (row: any) => {
  if (row) {
    // 编辑模式
    dialogTitle.value = '编辑客户';
    Object.assign(formData, row);
  } else {
    // 新增模式
    dialogTitle.value = '新增客户';
    resetForm();
  }
  dialogVisible.value = true;
};

// 重置表单
const resetForm = () => {
  formData.customerID = 0;
  formData.customercode = '';
  formData.customername = '';
  formData.customerrabbreviation = '';
  formData.contactinformationofCustomer = '';
  formData.customercreditcode = '';
  formData.customerraddress = '';
  formData.customercomments = '';
  formData.createName = '';
  formData.createTime = '';
  formData.updateTime = '';
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false;
  resetForm();
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;
  try {
    await formRef.value.validate();
    if (formData.customerID) {
      // 编辑操作
      await updateCustomer();
    } else {
      // 新增操作
      await addCustomer();
    }
  } catch (error) {
    return;
  }
};

// 新增客户
const addCustomer = async () => {
   {
    const response = await APIs.post('/api/Write/AddCustomer', formData);
    if (response.data.code === 100) {
      ElMessage.success('新增客户成功');
      dialogVisible.value = false;
      getCustomerList();
    }
  }
};

// 更新客户
const updateCustomer = async () => {
   {
    const response = await APIs.post('/api/Write/UpdateCustomer', formData);
    if (response.data.code === 100) {
      ElMessage.success('更新客户成功');
      dialogVisible.value = false;
      getCustomerList();
    }
  } 
};

// 删除单个客户
const handleDelete = async (row: any) => {
   {
    await ElMessageBox.confirm('确定要删除该客户吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });
    
    const response = await APIs.post('/api/Write/DeleCustomer', row);
    if (response.data.code === 100) {
      ElMessage.success('删除客户成功');
      getCustomerList();
    }
  }
}

const handleExport = async () => {
   {
    const response = await APIs.get('/api/Read/ExportCustomer', {
      params: {
        ...searchForm,
        Keyword: searchKeyword.value
      },
      responseType: 'blob'
    });
    
  } 
}
const handleSearch = () => {
  pagination.currentPage = 1;
  getCustomerList();
};
</script>

<style scoped>
.customer-container {
  padding: 20px;
  background-color: #f5f7fa;
  height: 100%;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 10px 15px;
  background-color: #e8ebf1;
  border-radius: 4px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.search-tools {
  display: flex;
  align-items: center;
  gap: 5px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.total-count {
  color: #606266;
  font-size: 14px;
}

.column-header-with-search {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-icon {
  cursor: pointer;
  font-size: 14px;
}

.column-search {
  margin-top: 5px;
}

.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s;
}

.fade-enter-from, .fade-leave-to {
  opacity: 0;
}
</style>